<?php
$bool_IE 	= false;

if( strpos( $_SERVER["HTTP_USER_AGENT"], "MSIE" ) !== false ) $bool_IE = true;

function category_multi_level($sParent, $sprefix = "",$i_selected_item, $arr_data) {

	//if($sParent == NULL)
	//	$arr_data = $this->arr_data;
	$arr_temp = array();
	foreach ( $arr_data as $key => $o_modelTemp) {
		if($o_modelTemp->parent == $sParent) {
			array_push($arr_temp, $o_modelTemp);
		}
	}

	foreach ( $arr_temp as $key => $o_modelTemp) {

		if($o_modelTemp->identification == $i_selected_item)
			echo "<option value='".$o_modelTemp->identification."' selected='selected'>".$sprefix.$o_modelTemp->name."</option>";
		else
			echo "<option value='".$o_modelTemp->identification."'>".$sprefix.$o_modelTemp->name."</option>";

		category_multi_level($o_modelTemp->identification,$sprefix."....",$i_selected_item, $arr_data);
	}
}
?>

<div>
    <div class="border_box">     

        <form class="form_input" action="" method="post" id="form_item" name="form_item">
            <fieldset class="border_radius_all">
                <legend></legend>

                <div class="form_input_row">
					<label class="label_title">Tiêu Đề:*</label>
					<input
						id			= "txt_title"
						name		= "txt_title"
						title		= "Tiêu Đề Bài Viết"
						type		= "text"
						value		= "<?php if(isset($o_model)) { echo $o_model->title;}?>"
						class		= "form_textbox textbox_css3"
						tabindex	= "1"
						onblur		= "validation_onblur(this,'lbl_title_validation')"
					/>
					<label
						id		= "lbl_title_validation" 
						class	= "lable_validation"
					>Bạn chưa nhập tên sản phẩm.</label>
				</div><!--End form_input_row Name-->
				
                <div class="form_input_row">
					<label class="label_title">URL Ảo:*</label>
					<input
						id			= "txt_url"
						name		= "txt_url"
						title		= "URL Ảo"
						type		= "text"
						value		= "<?php if(isset($o_model)) { echo $o_model->url_mapping;}?>"
						class		= "form_textbox textbox_css3"
						tabindex	= "2"
						onblur		= "validation_onblur(this,'lbl_url_validation')"
					/>
					<label
						id		= "lbl_url_validation"
						class	= "lable_validation"
					>Bạn chưa nhập url ảo.</label>
				</div><!--End form_input_row Name-->
				
				<div class="form_input_row">
					<label class="label_title">Danh Mục:*</label>
					
					<select 
						id		= "sl_category"
						name	= "sl_category"
						tabindex= "3"
						<?php
						if ($bool_IE != true)
							echo "class = 'form_combobox select_css3 select_two_arrown'";
						else
							echo "class = 'form_combobox'";
						?>
					>
						<?php
						if(isset($o_model))
							category_multi_level($sParent = 0, $sprefix = "",$o_model->article_category,$arr_data);
						else
							category_multi_level($sParent = 0, $sprefix = "",0,$arr_data);
						?>
					</select>
				</div><!--End form_input_row-->
								
                <div class="form_input_row">
					<label class="label_title">Tag:</label>
					<input
						id			= "txt_tag"
						name		= "txt_tag"
						title		= "Từ Khoá"
						type		= "text"
						value		= "<?php if(isset($o_model)) { echo $o_model->tag;}?>"
						class		= "form_textbox textbox_css3"
						tabindex	= "4"
					/>
				</div><!--End form_input_row Name-->
				
                <div class="form_input_row">
					<label class="label_title">Đã Kiểm Duyệt:</label>
					<div class="input_items_horizon">
						<input
							id			= "chk_approval"
							name		= "chk_approval"
							title		= "Đã Kiểm Duyệt"
							type		= "checkbox"
							tabindex	= "5"
							value		= "1"
							<?php if( isset($o_model) && $o_model->approval == 1) { echo "checked='checked'";}?>
						/>
					</div>
				</div><!--End form_input_row Name-->
				

                <div class="form_input_row">
					<label class="label_title"> </label>
					<img alt="preview" src="<?php if(isset($o_model)) { echo $o_model->image;}?>" class="image_preview" id="img_preview">
					<div class="input_items_horizon" id="div_imageUpload">
						<input
							id			= "txt_image"
							name		= "txt_image"
							title		= "Hình ảnh đại diện danh mục"
							type		= "text"
							value		= "<?php if(isset($o_model)) { echo $o_model->image;}?>"
							class		= "form_textbox textbox_css3"
							tabindex	= "6"
							style		= "width: 99%;"
						/><br/><br/>
						<input
							type	= "checkbox"
							id		= "chk_image"
							name	= "chk_image"
							onchange= "visible_uploadbox();"
						/> Upload hình lên máy chủ.
					</div>
					
				</div><!--End form_input_row-->
				<div class="clear"></div>
				
				<div class="form_input_row">
					<div class="title_full"> <strong>Mô Tả:</strong></div>
					<textarea
						id		= "ta_description"
						name	= "ta_description"
						rows	= "10"
						cols	= "40"
						tabindex="7"
					><?php if(isset($o_model)) { echo $o_model->description;}?></textarea>
				</div><!--End form_input_row-->
				
				<div class="form_input_row">
					<div class="title_full"> <strong>Nội Dung:</strong></div>
					<textarea
						id		= "ta_content"
						name	= "ta_content"
						rows	= "200"
						cols	= "40"
						tabindex="8"
					><?php if(isset($o_model)) { echo $o_model->content;}?></textarea>
				</div><!--End form_input_row-->
				
                <div class="form_input_row" style="border: none;">
					<div class="input_items_horizon">
						<input
							title		= "gửi yêu cầu"
							name		= "btn_save"
							id			= "btn_save"
							type		= "submit"
							value		= "Lưu"
							class		= "input_button button_css3"
							tabindex	= "9"
						/>
                        <input
							title		= "gửi yêu cầu"
							name		= "btn_cancel"
							id			= "btn_cancel"
							type		= "button"
							value		= "Hủy Bỏ"
							class		= "input_button button_css3"
							tabindex	= "10"
						/>
					</div><!--End input_items_horizon-->
				</div><!--End form_input_row button-->

            </fieldset>
        </form>

    </div><!--End box_950-->
</div><!--End container_960-->

<script type="text/javascript">

var ta_description, ta_content, html = '';

$(document).ready(function () {

	ta_description = CKEDITOR.replace( 'ta_description', {
		toolbar: [
	  		['Source'],
			[ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
			[ 'FontSize', 'TextColor', 'BGColor' ],
			[ 'UIColor' ]
		]
	}, html);


	ta_content = CKEDITOR.replace( 'ta_content', {}, html);

	$('#txt_name').focus();
});


function visible_uploadbox(){
	if(document.getElementById("chk_image").checked==true){

		var ct 	 ="<input type='file' id='file_image' name='file_image' class='form_textbox textbox_css3' style = 'width: 99%;' accept='image/*' onchange='ajaxFileUpload();'/><br/><br/>";
		ct 		+= "<input type='checkbox' id='chk_image' onchange='visible_uploadbox();' checked='checked' />";
		document.getElementById("div_imageUpload").innerHTML= ct;
		
	} else{

		var ct 	 = "<input id= 'txt_image'	type= 'text' name= 'txt_image' value= '<?php if(isset($o_model)) { echo $o_model->image;}?>'	class='form_textbox textbox_css3' style = 'width: 99%;'/><br/><br/>";
		ct 		+= "<input type='checkbox' id='chk_image' onchange='visible_uploadbox();'/> Upload hình lên máy chủ";
		document.getElementById("div_imageUpload").innerHTML= ct;
	}
}

						
$('#btn_cancel').click(function() {

	$("#dialog_notice").dialog("close");

	var i_key 	= <?=$i_key ?>;
	if(i_key != 0)
		$("#tr_"+i_key).css("background-color","#FFFFFF");
});

function validation_onblur( element, lbl_validation) {
	
	if( element.value == ""){
		$('#'+lbl_validation).fadeIn("slow", "linear");
		//$(element).focus();
	} else {
		$('#'+lbl_validation).fadeOut();
	}
}

$('#txt_title').blur(function(){
	var str = remove_utf8(this.value.toLowerCase());
	//alert(str);
	var special_character	= " ,@!/-#%&";//unavailable:$^*()
	for(var i = 0; i < special_character.length;i++){
		str = str.replace(new RegExp(special_character.charAt(i), 'g'),"-");
	}
	
	$('#txt_url').val(str);
});

function form_onsubmit(param)
{
	if ( $("#txt_title").val() == "" || $("#txt_title").val().length < 4 )
	{
		$("#lbl_title_validation").fadeIn("slow", "linear");
		$("#txt_title").focus();
		return false;
	}

	if ( $("#txt_url").val() == "" || $("#txt_url").val().length < 4)
	{
		$("#lbl_url_validation").fadeIn("slow", "linear");
		$("#txt_url").focus();
		return false;
	}
	
	return true;
}

//attach a submit handler to the form
$("#form_item").submit(function(event) {
	
	//stop form from submitting normally
	event.preventDefault();
	
	var bool_submit = form_onsubmit("form_item");
	if (bool_submit == true) {

		$( "#dialog_excute" ).dialog( "open" );
		var i_key = <?=$i_key ?>;
		var url_image = $("#img_preview").attr("src");

		if( typeof $("#txt_image").val() !="undefined" &&
			$("#txt_image").val() != ""
		)
			url_image = $("#txt_image").val();

		$.ajax({
			url			: "<?=Yii::app()->createUrl("article/save");?>",
			type		: "POST",
			contentType	: "application/x-www-form-urlencoded; charset=UTF-8",
			cache		: false,
			data		: {
				item_key 		: i_key,
				txt_title		: $("#txt_title").val(),
				sl_category		: $("#sl_category").val(),
				txt_urlMapping	: $("#txt_url").val(),
				txt_image		: url_image,
				txt_tag			: $("#txt_tag").val(),
				chk_approval	: ($("#chk_approval").is(':checked')? 1 : 0),
				ta_description	: ta_description.getData(),
				ta_content		: ta_content.getData()
			},
			success	: function(string){

				/**
				 * Kiểu mặc định trả về là dạng String, bạn dùng hàm parseJSON để phân tích dữ liệu trả về
				 * có 2 cách parse JSON là : JSON.parse() và $.parseJSON();
				 * 1. var getData = JSON.parse(string);
				 * 2. var getData = $.parseJSON(string);
				**/
				var arr_result = $.parseJSON(string);
				if(arr_result.error != null){
					alert(arr_result.error);
					$("#dialog_excute").dialog( "close" );
					return;
				}

				var ct_row = "";

				if(i_key != 0) {
					
					ct_row += "<td>";
					ct_row += "	<input";
					ct_row += "		id		= 'chk_delete'";
					ct_row += "		name	= 'chk_delete'";
					ct_row += "		type	= 'checkbox'";
					ct_row += "		class	= 'check_box'";
					ct_row += "		value	= '"+ arr_result.key +"'";
					ct_row += "		onclick='display_button(this);'";
					ct_row += "	/>";
					ct_row += "</td>";
					
					ct_row += "<td>";
					ct_row += "	<span";
					ct_row += "		class	= 'icon_button icon_edit'";
					ct_row += "		onclick	= \"call_edit_page("+ arr_result.key +");\"";
					ct_row += "	> ";
					ct_row += "	</span>";
					ct_row += "</td>";
									
					ct_row += "<td>" + arr_result.key			+ "</td>";
					ct_row += "<td>" + arr_result.title			+ "</td>";
					ct_row += "<td>" + arr_result.category_name	+ "</td>";
					ct_row += "<td>" + arr_result.description	+ "</td>";
					ct_row += "<td>" + arr_result.tag			+ "</td>";
					ct_row += "<td>" + arr_result.insert		+ "</td>";

					$("#tr_"+i_key).html(ct_row);

					$("#tr_"+i_key).css("background-color","#FFFFFF");

					$("#dialog_excute").dialog( "close" );
					$("#dialog_notice").dialog("close");

				} else if (i_key == 0) {
					
					alert("Thêm Thành Công");
					$("#dialog_excute").dialog( "close" );
					$('#txt_name').focus();
				}
			},
			error: function (){
				alert('Trang hiện hành không tồn tại.');
				$("#dialog_excute").dialog( "close" );
			}
		});//End Ajax
	}//End if (bool_submit == true)
	
});//End form submit


function ajaxFileUpload()
{
	var urlAction = "<?=Yii::app()->createUrl("article/UploadImage");?>";
	
	$.ajaxFileUpload ({
		url				: urlAction,
		secureuri		: false,
		fileElementId	: "file_image",
		dataType		: "json",
		data:{
			id_item			: "id",
			url_image		: "images/image_article",
			fileInputName	: "file_image",
			width_image		: 160,
			height_image	: 120
		},
		success: function (data, status)
		{
			if(typeof(data.error) != "undefined")
			{
				alert(data.error);
			}
			else
			{
				var url_image = "<?=Yii::app()->baseUrl;?>/" + data.result;
				$("#img_preview").attr("src", url_image);
			}
		},
		error: function (data, status, e)
		{
			alert(e);
		}
	});
	
	return false;
}//end ajaxFileUpload(urlAction)
</script>